package com.zhiche.lisa.tms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.zhiche.lisa.core.enums.CommonEnum;
import com.zhiche.lisa.core.enums.SystemEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.redislog.RedisLogUtil;
import com.zhiche.lisa.oms.dto.HuiyuncheCancleDTO;
import com.zhiche.lisa.tms.dao.model.Shipment;
import com.zhiche.lisa.tms.dao.model.bo.ShipToByLicenseBO;
import com.zhiche.lisa.tms.service.IShipmentPositionService;
import com.zhiche.lisa.tms.service.IShipmentService;
import com.zhiche.lisa.tms.vo.ShipmentListInfoVo;
import com.zhiche.lisa.tms.vo.ShipmentListVo;
import com.zhiche.lisa.tms.vo.ShipmentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ship")
@Api(value = "/ship", description = "装车单接口", tags = {"装车单接口"})
public class ShipmentController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShipmentController.class);

    @Autowired
    private IShipmentService shipmentService;

    @Autowired
    private IShipmentPositionService shipmentPositionService;

    @Value("${logRedis.isTest}")
    private boolean isTest;


    @PostMapping(value = "/shiplistbydriverId")
    @ApiOperation(value = "根据司机ID查询车装车单", notes = "根据司机ID查询车装车单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Page<ShipmentListVo>> shiplistbydriverId(@RequestBody Page<Shipment> page, HttpServletRequest request) {
        LOGGER.info("ShipmentController.shiplistbydriverId（根据司机ID查询车装车单） params : {} ", JSON.toJSONString(page));
        RestfulResponse<Page<ShipmentListVo>> result = new RestfulResponse<>(0, "success", null);
        try {
            Page<ShipmentListVo> pageVo = shipmentService.getShipmentListVoByDriverId(page, request);
            result.setData(pageVo);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.shiplistbydriverId ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("BankController.vagueSelectLsp ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @GetMapping(value = "/getShipDeteailById/{id}")
    @ApiOperation(value = "根据ID得到装车单详情", notes = "根据ID得到装车单详情", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<ShipmentVo> getShipDeteailById(@PathVariable Long id, HttpServletRequest request) {
        LOGGER.info("ShipmentController.getShipDeteailById（模糊查询银行信息） params : {} ", id);
        RestfulResponse<ShipmentVo> result = new RestfulResponse<>(0, "success", null);
        try {
            ShipmentVo shipmentVo = shipmentService.getShipDeteailById(id, request);
            result.setData(shipmentVo);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.getShipDeteailById ERROR... ", e);
            result = new RestfulResponse<>(e.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("BankController.getShipDeteailById ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;

    }

    @PostMapping(value = "/shipToByLicense")
    @ApiOperation(value = "根据车牌号运抵", notes = "根据车牌号运抵", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse shipToByLicense(@RequestBody ShipToByLicenseBO shipToByLicenseBO, @RequestHeader("Authorization") String token) {
        LOGGER.info("ShipmentController.shipToByLicense（根据车牌号运抵） params : {} ", shipToByLicenseBO.toString());
        RestfulResponse result = new RestfulResponse<>(0, "success", null);

        try {
            shipmentService.shipToByLicense(shipToByLicenseBO, token);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.shipToByLicense ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipmentController.shipToByLicense ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }

        return result;
    }

    @GetMapping(value = "/currrentUploadCount/{shipmentCode}")
    @ApiOperation(value = "统计当天上报数", notes = "统计当天上报数", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Map<String, Object>> currrentUploadCount(@PathVariable String shipmentCode) {
        LOGGER.info("ShipmentController.currrentUploadCount（统计当天上报数） params : {} ", shipmentCode);
        RestfulResponse<Map<String, Object>> result = null;

        try {
            result = new RestfulResponse<>(0, "success", shipmentPositionService.currrentUploadCount(shipmentCode));
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.currrentUploadCount BaseException... ", e);
            result = new RestfulResponse<>(-1, e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipmentController.currrentUploadCount ERROR... ", e);
            result = new RestfulResponse<>(-1, "系统异常", null);
        }

        return result;
    }

    @PostMapping(value = "/positionUpload")
    @ApiOperation(value = "位置上报", notes = "位置上报", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse positionUpload(@RequestBody ShipToByLicenseBO shipToByLicenseBO, @RequestHeader("Authorization") String token) {
        LOGGER.info("ShipmentController.positionUpload（位置上报） params : {} ", shipToByLicenseBO.toString());
        RestfulResponse result = null;

        try {
            shipmentService.positionUpload(shipToByLicenseBO, token);
            result = new RestfulResponse<>(0, "success", null);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.positionUpload BaseException... ", e);
            result = new RestfulResponse<>(-1, e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipmentController.positionUpload ERROR... ", e);
            result = new RestfulResponse<>(-1, e.getMessage(), null);
        }

        return result;
    }

    @PostMapping(value = "/shiplistbyTenanId")
    @ApiOperation(value = "根据租户ID查询运单", notes = "根据租户ID查询运单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Page<ShipmentListVo>> shipListbyTenanId(@RequestBody Page<Shipment> page, HttpServletRequest request) {
        LOGGER.info("ShipmentController.shipListbyTenanId（根据租户ID查询车装车单） params : {} ", page);
        RestfulResponse<Page<ShipmentListVo>> result = new RestfulResponse<>(0, "success", null);
        try {
            Page<ShipmentListVo> pageVo = shipmentService.getShipmentListVoByTenanId(page, request);
            result.setData(pageVo);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.shipListbyTenanId ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("BankController.vagueSelectLsp ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @GetMapping(value = "/driverWaybill")
    @ApiOperation(value = "根据司机id判断是否有未完成的订单", notes = "根据司机id判断是否有未完成的订单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Boolean> driverWaybill(@RequestParam Long DriverId) {
        LOGGER.info("ShipmentController.driverWaybill（根据司机id判断是否有未完成的订单） params : {} ", DriverId);
        RestfulResponse<Boolean> result = new RestfulResponse<>(0, "success", null);
        try {
            result.setData(shipmentService.driverWaybill(DriverId));
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.driverWaybill ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("BankController.driverWaybill ERROR... ", e);
        }
        return result;
    }

    @GetMapping(value = "/lspWaybill")
    @ApiOperation(value = "根据承运商id判断是否有未完成的订单", notes = "根据承运商id判断是否有未完成的订单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Boolean> lspWaybill(@RequestParam String lspId) {
        LOGGER.info("ShipmentController.lspWaybill（根据承运商id判断是否有未完成的订单） params : {} ", lspId);
        RestfulResponse<Boolean> result = new RestfulResponse<>(0, "success", null);
        try {
            result.setData(shipmentService.lspWaybill(lspId));
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.lspWaybill ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("BankController.lspWaybill ERROR... ", e);
        }
        return result;
    }

    @GetMapping(value = "/fleetWaybill")
    @ApiOperation(value = "根据车队id判断是否有未完成的订单", notes = "根据车队id判断是否有未完成的订单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Boolean> fleetWaybill(@RequestParam("fleetId") String fleetId) {
        LOGGER.info("ShipmentController.fleetWaybill（根据车队id判断是否有未完成的订单） params : {} ", fleetId);
        RestfulResponse<Boolean> result = new RestfulResponse<>(0, "success", null);
        try {
            result.setData(shipmentService.fleetWaybill(fleetId));
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.fleetWaybill ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("BankController.fleetWaybill ERROR... ", e);
        }
        return result;
    }

    @GetMapping(value = "/getDriverShipDeteailById/{id}")
    @ApiOperation(value = "司机根据ID得到装车单详情", notes = "司机根据ID得到装车单详情", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<ShipmentVo> getDriverShipDeteailById(@PathVariable Long id, HttpServletRequest request) {
        LOGGER.info("ShipmentController.getDriverShipDeteailById（司机根据ID得到装车单详情） params : {} ", id);
        RestfulResponse<ShipmentVo> result = new RestfulResponse<>(0, "success", null);
        try {
            ShipmentVo shipmentVo = shipmentService.getDriverShipDeteailById(id, request);
            result.setData(shipmentVo);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.getDriverShipDeteailById ERROR... ", e);
            result = new RestfulResponse<>(e.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("BankController.getDriverShipDeteailById ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;

    }

    @PostMapping(value = "/peopleSendDepartureConfirmation")
    @ApiOperation(value = "人送发车确认", notes = "人送发车确认", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Object> peopleSendDepartureConfirmation(@RequestBody HuiyuncheCancleDTO infoDTO) {
        LOGGER.info("ShipmentController.peopleSendDepartureConfirmation（人送发车确认） params : {} ", JSONObject.toJSONString(infoDTO));
        RestfulResponse<Object> result = new RestfulResponse<>(0, "success", null);
        try {
            //系统交互接收日志记录
            RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), infoDTO.getOrderCode(), JSONObject.toJSONString(infoDTO),
                    "/ship/peopleSendDepartureConfirmation", 2, 1, "", isTest);

            shipmentService.peopleSendDepartureConfirmation(infoDTO,null);

            //系统交互处理日志记录（成功）
            RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), infoDTO.getOrderCode(), JSONObject.toJSONString(infoDTO),
                    "/ship/peopleSendDepartureConfirmation", 3, 1, "", isTest);
        } catch (BaseException e) {
            //系统交互处理日志记录（失败）
            RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), infoDTO.getOrderCode(), JSONObject.toJSONString(infoDTO),
                    "/ship/peopleSendDepartureConfirmation", 3, 0, e.getMessage(), isTest);

            LOGGER.error("ShipmentController.peopleSendDepartureConfirmation ERROR... ", e, isTest);
            result = new RestfulResponse<>(e.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            //系统交互处理日志记录（失败）
            RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), infoDTO.getOrderCode(), JSONObject.toJSONString(infoDTO),
                    "/ship/peopleSendDepartureConfirmation", 3, 0, CommonEnum.ERROR.getText(), isTest);

            LOGGER.error("BankController.peopleSendDepartureConfirmation ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;

    }

    @PostMapping(value = "/peopleSendShippingTo")
    @ApiOperation(value = "人送运抵", notes = "人送运抵", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Object> peopleSendShippingTo(@RequestBody HuiyuncheCancleDTO infoDTO) {
        LOGGER.info("ShipmentController.peopleSendShippingTo（人送运抵） params : {} ", JSONObject.toJSONString(infoDTO));
        RestfulResponse<Object> result = new RestfulResponse<>(0, "success", null);
        try {
            //系统交互接收日志记录
            RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), infoDTO.getOrderCode(), JSONObject.toJSONString(infoDTO),
                    "/ship/peopleSendShippingTo", 2, 1, "", isTest);

            shipmentService.peopleSendShippingTo(infoDTO);

            //系统交互处理日志记录（成功）
            RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), infoDTO.getOrderCode(), JSONObject.toJSONString(infoDTO),
                    "/ship/peopleSendShippingTo", 3, 1, "", isTest);
        } catch (BaseException e) {
            //系统交互处理日志记录（失败）
            RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), infoDTO.getOrderCode(), JSONObject.toJSONString(infoDTO),
                    "/ship/peopleSendShippingTo", 3, 0, e.getMessage(), isTest);
            LOGGER.error("ShipmentController.peopleSendShippingTo ERROR... ", e);
            result = new RestfulResponse<>(e.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            //系统交互处理日志记录（失败）
            RedisLogUtil.addSysLogs(SystemEnum.INTEGRATION.getCode(), SystemEnum.OMS.getCode(), infoDTO.getOrderCode(), JSONObject.toJSONString(infoDTO),
                    "/ship/peopleSendShippingTo", 3, 0, CommonEnum.ERROR.getText(), isTest);
            LOGGER.error("BankController.peopleSendShippingTo ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;

    }

    @PostMapping(value = "/shipAttachlist")
    @ApiOperation(value = "查看重载指令列表", notes = "查看重载指令列表", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Page<ShipmentListVo>> shipAttachlist(@RequestBody Page<Shipment> page) {
        LOGGER.info("ShipmentController.shipAttachlist（查看重载指令列表） params : {} ", JSON.toJSONString(page));
        RestfulResponse<Page<ShipmentListVo>> result = new RestfulResponse<>(0, "success", null);
        try {
            Page<ShipmentListVo> pageVo = shipmentService.getShipAttachlist(page);
            result.setData(pageVo);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.shipAttachlist ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipmentController.shipAttachlist ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/shipToProvince")
    @ApiOperation(value = "无人车承运重推省平台", notes = "无人车承运重推省平台", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Object> shipToProvince(String shipmentId, @RequestHeader("Authorization") String token) {
        LOGGER.info("ShipmentController.shipToProvince（无人车承运重推省平台） params : {} ", shipmentId);
        RestfulResponse<Object> result = new RestfulResponse<>(0, "success", null);
        try {
           shipmentService.shipToProvince(shipmentId,token);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.shipToProvince ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipmentController.shipToProvince ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/shipListByFleetId")
    @ApiOperation(value = "根据车队ID查询装车单", notes = "根据车队ID查询装车单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<Page<ShipmentListInfoVo>> shipListByFleetId(@RequestBody Page<Shipment> page, @RequestHeader("Authorization") String token) {
        LOGGER.info("ShipmentController.shiplistbydriverId（根据车队ID查询装车单） params : {} ", JSON.toJSONString(page));
        RestfulResponse<Page<ShipmentListInfoVo>> result = new RestfulResponse<>(0, "success", null);
        try {
            Page<ShipmentListInfoVo> pageVo = shipmentService.getShipmentListVoByFleetId(page, token);
            result.setData(pageVo);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.shipListByFleetId ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipmentController.shipListByFleetId ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/exportShipByFleetId")
    @ApiOperation(value = "根据车队ID导出装车单", notes = "根据车队ID导出装车单", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<List<ShipmentListInfoVo>> exportShipByFleetId(@RequestBody Map<String ,Object> page, @RequestHeader("Authorization") String token) {
        LOGGER.info("ShipmentController.exportShipByFleetId（根据车队ID导出装车单） params : {} ", JSON.toJSONString(page));
        RestfulResponse<List<ShipmentListInfoVo>> result = new RestfulResponse<>(0, "success", null);
        try {
            List<ShipmentListInfoVo> pageVo = shipmentService.exportShipByFleetId(page, token);
            result.setData(pageVo);
        } catch (BaseException e) {
            LOGGER.error("ShipmentController.exportShipByFleetId ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipmentController.exportShipByFleetId ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;
    }

    @PostMapping(value = "/getShipSourceKeys")
    @ApiOperation(value = "获取当天所有指令号", notes = "获取当天所有指令号", produces = MediaType.APPLICATION_JSON_VALUE, response = RestfulResponse.class)
    public RestfulResponse<List<String>> getShipSourceKeys() {
        LOGGER.info("ShipmentController.getShipSourceKeys（获取当天所有指令号）start");
        RestfulResponse<List<String>> result = new RestfulResponse<>(0, "success", null);
        try {
            List<String> shipSourceKeys = shipmentService.getShipSourceKeys();
            result.setData(shipSourceKeys);
        } catch (BaseException ex) {
            LOGGER.error("ShipmentController.getShipSourceKeys ERROR...{} ", ex.getMessage());
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), ex.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("ShipmentController.getShipSourceKeys ERROR... ", e);
            result = new RestfulResponse<>(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return result;

    }


}
